package net.superdvach.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import net.superdvach.core.Core;
import net.superdvach.network.NetworkLayer;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;

import freemarker.template.Template;
import freemarker.template.TemplateException;

public class SettingsHandler implements HttpHandler {

	public SettingsHandler(WebClient parent) {
		m_parent = parent;
	}

	@Override
	public void handle(HttpExchange exchange) throws IOException {
		String subaction = getParam(exchange.getRequestURI().getQuery(), "subaction");
		if(subaction == null) {
			settingsHome(exchange);
		}
		else if(subaction.equals("addlayer")) {
			settingsAddLayer(exchange);
		}
	}
	
	private void settingsAddLayer(HttpExchange exchange) throws IOException {
		PrintWriter out = new PrintWriter(exchange.getResponseBody());
		exchange.sendResponseHeaders(200, 0);
		Template tpl = m_parent.templateEngine().getTemplate("settings_addlayer.htpl");
		try {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("s2ch", m_parent.dataRoot());
			map.put("networkLayers", Core.getNetworkLayerManager().availableLayers());
			tpl.process(map, out);
		} catch (TemplateException e) {
			// TODO Auto-generated catch block
			logger.debug(e.getMessage());
			e.printStackTrace();
		}
		out.close();
	}

	private void settingsHome(HttpExchange exchange) throws IOException {
		PrintWriter out = new PrintWriter(exchange.getResponseBody());
		exchange.sendResponseHeaders(200, 0);
		Template tpl = m_parent.templateEngine().getTemplate("settings.htpl");
		try {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("s2ch", m_parent.dataRoot());
			map.put("networkLayers", layersMap());
			tpl.process(map, out);
		} catch (TemplateException e) {
			// TODO Auto-generated catch block
			logger.debug(e.getMessage());
			e.printStackTrace();
		}
		out.close();
	}
	
	private List<Map<String, String>> layersMap() {
		List<Map<String, String>> list = new ArrayList<Map<String, String>>();
		int totalLayers = Core.getNetworkLayerManager().layerCount();
		for(int i = 0; i < totalLayers; i++) {
			NetworkLayer l = Core.getNetworkLayerManager().layer(i);
			Map<String, String> layer = new HashMap<String, String>();
			layer.put("name", l.humanReadableName());
			layer.put("type", l.layerType());
			list.add(layer);
		}
		return list;
	}
	
	private String getParam(String query, String param) {
		if(query == null)
			return null;
		String[] parameters = query.split("&");
		for(String p : parameters) {
			String[] parts = p.split("=");
			if(parts.length == 2 && parts[0].equals(param)) {
				return parts[1]; 
			}
		}
		return null;
	}

	private WebClient m_parent;
	static Logger logger = Logger.getLogger(WebClient.class);
}
